/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package formatconverter;

import java.util.Vector;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
 * @author Leo Lira
 */
public class HelloMIDlet extends MIDlet implements CommandListener, ItemStateListener {

    private boolean midletPaused = false;
    private static int operation;
//<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Command exitCommand;
    private Command okCommand;
    private Command backCommand;
    private Form principal;
    private ChoiceGroup choiceGroup;
    private TextField txtNumEntrada;
    private Form conversao;
    private ChoiceGroup choiceGroup1;
    private TextField textField;
//</editor-fold>//GEN-END:|fields|0|

    /**
     * The HelloMIDlet constructor.
     */
    public HelloMIDlet() {
    }

//<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
//</editor-fold>//GEN-END:|methods|0|
//<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initializes the application. It is called only once when the MIDlet is
     * started. The method is called before the
     * <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
//</editor-fold>//GEN-END:|0-initialize|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getPrincipal());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
    }//GEN-BEGIN:|3-startMIDlet|2|
//</editor-fold>//GEN-END:|3-startMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
//</editor-fold>//GEN-END:|4-resumeMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The
     * <code>display</code> instance is taken from
     * <code>getDisplay</code> method. This method is used by all actions in the
     * design for switching displayable.
     *
     * @param alert the Alert which is temporarily set to the display;
     * if <code>null</code>, then <code>nextDisplayable</code> is set
     * immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
//</editor-fold>//GEN-END:|5-switchDisplayable|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a
     * particular displayable.
     *
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == conversao) {//GEN-BEGIN:|7-commandAction|1|39-preAction
            if (command == backCommand) {//GEN-END:|7-commandAction|1|39-preAction
                switchDisplayable(null, getPrincipal()); 
//GEN-LINE:|7-commandAction|2|39-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|3|19-preAction
        } else if (displayable == principal) {
            if (command == exitCommand) {//GEN-END:|7-commandAction|3|19-preAction
                // write pre-action user code here
                exitMIDlet();//GEN-LINE:|7-commandAction|4|19-postAction
                // write post-action user code here
            } else if (command == okCommand) {//GEN-LINE:|7-commandAction|5|24-preAction
             
//                switchDisplayable(null, getConversao());                                           
                // write post-action user code hereif (choiceGroup.isSelected(0)) {
               
                if (choiceGroup.isSelected(0)) {

                    operation = 0;
                    if (isBinary(txtNumEntrada.getString())) {
                        switchDisplayable(null, getConversao());//GEN-LINE:|7-commandAction|6|24-postAction
                    } else {
                        Alert a = new Alert("Formato errado!");
                        a.setString("Verifique o formato do nÃºmero digitado.");
                        a.setTimeout(5000);
                        getDisplay().setCurrent(a);
                    }

                } else if (choiceGroup.isSelected(1)) {
             

                    operation = 1;

                    switchDisplayable(null, getConversao());

                } else if (choiceGroup.isSelected(2)) {

                    operation = 2;
                    switchDisplayable(null, getConversao());

                } else if (choiceGroup.isSelected(3)) {

                    operation = 3;
                    switchDisplayable(null, getConversao());
                }


            }//GEN-BEGIN:|7-commandAction|7|7-postCommandAction
        }//GEN-END:|7-commandAction|7|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|8|
//</editor-fold>//GEN-END:|7-commandAction|8|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|18-getter|0|18-preInit
    /**
     * Returns an initialized instance of exitCommand component.
     *
     * @return the initialized component instance
     */
    public Command getExitCommand() {
        if (exitCommand == null) {//GEN-END:|18-getter|0|18-preInit
            // write pre-init user code here
            exitCommand = new Command("Exit", Command.EXIT, 0);//GEN-LINE:|18-getter|1|18-postInit
            // write post-init user code here
        }//GEN-BEGIN:|18-getter|2|
        return exitCommand;
    }
//</editor-fold>//GEN-END:|18-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: principal ">//GEN-BEGIN:|14-getter|0|14-preInit
    /**
     * Returns an initialized instance of principal component.
     *
     * @return the initialized component instance
     */
    public Form getPrincipal() {
        if (principal == null) {//GEN-END:|14-getter|0|14-preInit
            // write pre-init user code here
            principal = new Form("Format Converter", new Item[]{getChoiceGroup(), getTxtNumEntrada()});//GEN-BEGIN:|14-getter|1|14-postInit
            principal.addCommand(getExitCommand());
            principal.addCommand(getOkCommand());
            principal.setCommandListener(this);//GEN-END:|14-getter|1|14-postInit
            // write post-init user code here
        }//GEN-BEGIN:|14-getter|2|
        return principal;
    }
//</editor-fold>//GEN-END:|14-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand ">//GEN-BEGIN:|23-getter|0|23-preInit
    /**
     * Returns an initialized instance of okCommand component.
     *
     * @return the initialized component instance
     */
    public Command getOkCommand() {
        if (okCommand == null) {//GEN-END:|23-getter|0|23-preInit
            // write pre-init user code here
            okCommand = new Command("Ok", Command.OK, 0);//GEN-LINE:|23-getter|1|23-postInit
            // write post-init user code here
        }//GEN-BEGIN:|23-getter|2|
        return okCommand;
    }
//</editor-fold>//GEN-END:|23-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: conversao ">//GEN-BEGIN:|22-getter|0|22-preInit
    /**
     * Returns an initialized instance of conversao component.
     *
     * @return the initialized component instance
     */
    public Form getConversao() {
        if (conversao == null) {//GEN-END:|22-getter|0|22-preInit
            // write pre-init user code here
            conversao = new Form("Format Converter", new Item[]{getChoiceGroup1(), getTextField()});//GEN-BEGIN:|22-getter|1|22-postInit
            conversao.addCommand(getBackCommand());
            conversao.setCommandListener(this);//GEN-END:|22-getter|1|22-postInit
            conversao.setItemStateListener(this);
        }//GEN-BEGIN:|22-getter|2|
        return conversao;
    }
//</editor-fold>//GEN-END:|22-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: choiceGroup ">//GEN-BEGIN:|25-getter|0|25-preInit
    /**
     * Returns an initialized instance of choiceGroup component.
     *
     * @return the initialized component instance
     */
    public ChoiceGroup getChoiceGroup() {
        if (choiceGroup == null) {//GEN-END:|25-getter|0|25-preInit
            // write pre-init user code here
            choiceGroup = new ChoiceGroup("Escolha o formato de Entrada:", Choice.EXCLUSIVE);//GEN-BEGIN:|25-getter|1|25-postInit
            choiceGroup.append("Bin\u00E1rio:", null);
            choiceGroup.append("Decimal", null);
            choiceGroup.append("Hexadecimal", null);
            choiceGroup.append("Octal", null);
            choiceGroup.setSelectedFlags(new boolean[]{false, false, false, false});//GEN-END:|25-getter|1|25-postInit
            // write post-init user code here
        }//GEN-BEGIN:|25-getter|2|
        return choiceGroup;
    }
//</editor-fold>//GEN-END:|25-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: txtNumEntrada ">//GEN-BEGIN:|30-getter|0|30-preInit
    /**
     * Returns an initialized instance of txtNumEntrada component.
     *
     * @return the initialized component instance
     */
    public TextField getTxtNumEntrada() {
        if (txtNumEntrada == null) {//GEN-END:|30-getter|0|30-preInit
            // write pre-init user code here
            txtNumEntrada = new TextField("Digite o n\u00FAmero:", "0", 32, TextField.ANY);//GEN-LINE:|30-getter|1|30-postInit
            // write post-init user code here
        }//GEN-BEGIN:|30-getter|2|
        return txtNumEntrada;
    }
//</editor-fold>//GEN-END:|30-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: choiceGroup1 ">//GEN-BEGIN:|32-getter|0|32-preInit
    /**
     * Returns an initialized instance of choiceGroup1 component.
     *
     * @return the initialized component instance
     */
    public ChoiceGroup getChoiceGroup1() {
        if (choiceGroup1 == null) {//GEN-END:|32-getter|0|32-preInit
            // write pre-init user code here
            choiceGroup1 = new ChoiceGroup("Escolha o formato de Sa\u00EDda:", Choice.EXCLUSIVE);//GEN-BEGIN:|32-getter|1|32-postInit
            choiceGroup1.append("Bin\u00E1rio", null);
            choiceGroup1.append("Decimal", null);
            choiceGroup1.append("Hexadecimal", null);
            choiceGroup1.append("Octal", null);
            choiceGroup1.setSelectedFlags(new boolean[]{false, false, false, false});//GEN-END:|32-getter|1|32-postInit
            // write post-init user code here
        }//GEN-BEGIN:|32-getter|2|
        return choiceGroup1;
    }
//</editor-fold>//GEN-END:|32-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: textField ">//GEN-BEGIN:|37-getter|0|37-preInit
    /**
     * Returns an initialized instance of textField component.
     *
     * @return the initialized component instance
     */
    public TextField getTextField() {
        if (textField == null) {//GEN-END:|37-getter|0|37-preInit
            // write pre-init user code here
            textField = new TextField("Resultado:", "0", 32, TextField.ANY | TextField.UNEDITABLE);//GEN-LINE:|37-getter|1|37-postInit
            
        }//GEN-BEGIN:|37-getter|2|
        return textField;
    }
//</editor-fold>//GEN-END:|37-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|38-getter|0|38-preInit
    /**
     * Returns an initialized instance of backCommand component.
     *
     * @return the initialized component instance
     */
    public Command getBackCommand() {
        if (backCommand == null) {//GEN-END:|38-getter|0|38-preInit
            // write pre-init user code here
            backCommand = new Command("Back", Command.BACK, 0);//GEN-LINE:|38-getter|1|38-postInit
            // write post-init user code here
        }//GEN-BEGIN:|38-getter|2|
        return backCommand;
    }
//</editor-fold>//GEN-END:|38-getter|2|

    /**
     * Returns a display instance.
     *
     * @return the display instance.
     */
    public Display getDisplay() {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable(null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started. Checks whether the MIDlet have been
     * already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet();
        } else {
            initialize();
            startMIDlet();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     *
     * @param unconditional if true, then the MIDlet has to be unconditionally
     * terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

    public void itemStateChanged(Item item) {
      

        switch (operation) {

            case 0:
                if (choiceGroup1.isSelected(0)) {
                    textField.setString(txtNumEntrada.getString());
                } else if (choiceGroup1.isSelected(1)) {
                    textField.setString(String.valueOf(binaryToDecimal(txtNumEntrada.getString())));
                } else if (choiceGroup1.isSelected(2)) {
                    textField.setString(String.valueOf(decimalToHexadecimal(String.valueOf(binaryToDecimal(txtNumEntrada.getString())))));
                } else if (choiceGroup1.isSelected(3)) {
                    textField.setString(String.valueOf(decimalToOctal(String.valueOf(binaryToDecimal(txtNumEntrada.getString())))));
                }
                break;

            case 1:
       
                if (choiceGroup1.isSelected(0)) {
         

                    textField.setString(decimalToBinary(txtNumEntrada.getString()));
                } else if (choiceGroup1.isSelected(1)) {
                    textField.setString(txtNumEntrada.getString());
                } else if (choiceGroup1.isSelected(2)) {
                    textField.setString(decimalToHexadecimal(txtNumEntrada.getString()));
                } else if (choiceGroup1.isSelected(3)) {
                    textField.setString(decimalToOctal(txtNumEntrada.getString()));
                }
                break;

            case 2:
                if (choiceGroup1.isSelected(0)) {
                    textField.setString(String.valueOf(decimalToBinary(hexadecimalToDecimal(txtNumEntrada.getString()))));
                } else if (choiceGroup1.isSelected(1)) {
                    textField.setString(hexadecimalToDecimal(txtNumEntrada.getString()));
                } else if (choiceGroup1.isSelected(2)) {
                    textField.setString(txtNumEntrada.getString());
                } else if (choiceGroup1.isSelected(3)) {
                    textField.setString(String.valueOf(decimalToOctal(hexadecimalToDecimal(txtNumEntrada.getString()))));
                }
                break;

            case 3:
                if (choiceGroup1.isSelected(0)) {
                    textField.setString(String.valueOf(decimalToBinary(octalToDecimal(txtNumEntrada.getString()))));
                } else if (choiceGroup1.isSelected(1)) {
                    textField.setString(octalToDecimal(txtNumEntrada.getString()));
                } else if (choiceGroup1.isSelected(2)) {
                    textField.setString(String.valueOf(decimalToHexadecimal(octalToDecimal(txtNumEntrada.getString()))));
                } else if (choiceGroup1.isSelected(3)) {
                    textField.setString(txtNumEntrada.getString());

                }
                break;

        }
    }

    public String decimalToOctal(String number) {
        Vector vetOcta = new Vector();
        int tempNum = Integer.parseInt(number);
        StringBuffer octaNum = new StringBuffer("");



        while (tempNum >= 8) {
            vetOcta.addElement(new Integer(tempNum % 8));
            tempNum = (int) Math.floor(tempNum / 8);
        }

        for (int i = 0; i < vetOcta.size(); i++) {
            int num = Integer.parseInt(vetOcta.elementAt(i).toString());
            octaNum.append(String.valueOf(num));
        }

        octaNum.append(String.valueOf(tempNum));

        return octaNum.reverse().toString();
    }

    public String octalToDecimal(String number) {

        int numTemp = 0;
        Vector v = new Vector();
        int index;

        for (int i = 0; i < number.length(); i++) {
            v.addElement(new Integer(Integer.parseInt(String.valueOf(number.charAt(i)))));
        }

        index = v.size() - 1;
        MathPow mp = new MathPow();
        for (int j = 0; j < v.size(); j++) {

            Double pot = new Double(mp.pow(8, index));
            index--;

            Integer element = (Integer) v.elementAt(j);


            int n = pot.intValue();

            if (index == -1) {
                numTemp = numTemp + 1;
            } else {
                numTemp = numTemp + (n * element.intValue());
            }
        }


        return String.valueOf(numTemp);
    }

    public String hexadecimalToDecimal(String number) {

        int numTemp = 0;
        Vector v = new Vector();
        int index;
        for (int i = 0; i < number.length(); i++) {

            if (number.charAt(i) == 'A') {
                v.addElement(new Integer(10));
            } else if (number.charAt(i) == 'B') {
                v.addElement(new Integer(11));

            } else if (number.charAt(i) == 'C') {
                v.addElement(new Integer(12));
            } else if (number.charAt(i) == 'D') {
                v.addElement(new Integer(13));
            } else if (number.charAt(i) == 'E') {
                v.addElement(new Integer(14));
            } else if (number.charAt(i) == 'F') {
                v.addElement(new Integer(15));
            } else {
                v.addElement(new Integer(Integer.parseInt(String.valueOf(number.charAt(i)))));
            }


        }


        index = v.size() - 1;
        MathPow mp = new MathPow();
        for (int j = 0; j < v.size(); j++) {

            Double pot = new Double(mp.pow(16, index));
            index--;

            Integer element = (Integer) v.elementAt(j);


            int n = pot.intValue();

            if (index == -1) {
                numTemp = numTemp + 1;
            } else {
                numTemp = numTemp + (n * element.intValue());
            }
        }


        return String.valueOf(numTemp);

    }

    public String decimalToHexadecimal(String number) {

        Vector vetHexa = new Vector();
        int tempNum = Integer.parseInt(number);
        StringBuffer hexaNum = new StringBuffer("");



        while (tempNum >= 16) {
            vetHexa.addElement(new Integer(tempNum % 16));
            tempNum = (int) Math.floor(tempNum / 16);
        }

        for (int i = 0; i < vetHexa.size(); i++) {
            int num = Integer.parseInt(vetHexa.elementAt(i).toString());

            switch (num) {

                case 10:
                    hexaNum.append("A");
                    break;
                case 11:
                    hexaNum.append("B");
                    break;
                case 12:
                    hexaNum.append("C");
                    break;
                case 13:
                    hexaNum.append("D");
                    break;
                case 14:
                    hexaNum.append("E");
                    break;
                case 15:
                    hexaNum.append("F");
                    break;
                default:
                    hexaNum.append(String.valueOf(num));

            }
        }
        switch (tempNum) {
            case 10:
                hexaNum.append("A");
                break;
            case 11:
                hexaNum.append("B");
                break;
            case 12:
                hexaNum.append("C");
                break;
            case 13:
                hexaNum.append("D");
                break;
            case 14:
                hexaNum.append("E");
                break;
            case 15:
                hexaNum.append("F");
                break;
            default:
                hexaNum.append(String.valueOf(tempNum));

        }

        return hexaNum.reverse().toString();



    }

    public String decimalToBinary(String number) {

        Vector vetBinary = new Vector();
        int tempNum = Integer.parseInt(number);
        StringBuffer binaryNum = new StringBuffer("");



        while (tempNum > 0) {
            vetBinary.addElement(new Integer(tempNum % 2));
            tempNum = (int) Math.floor(tempNum / 2);
        }

        for (int i = 0; i < vetBinary.size(); i++) {
            binaryNum.append(String.valueOf(vetBinary.elementAt(i)));
        }


        return binaryNum.toString();
    }

    public int binaryToDecimal(String number) {

        char[] charBinaryNum = number.toCharArray();

        int[] charFactor = new int[charBinaryNum.length];
        int factor = 1;
        int tempNum = 0;
        int index = charBinaryNum.length - 1;

        for (int i = 0; i < charBinaryNum.length; i++) {
            factor = factor * 2;
            charFactor[index] = factor / 2;
            index--;
        }

        for (int j = 0; j < charFactor.length; j++) {

            if (charBinaryNum[j] == '1') {
                tempNum = tempNum + charFactor[j];
            }
        }
        return tempNum;
    }

    public boolean isBinary(String number) {

        char[] charBinaryNum = number.toCharArray();
        boolean isBinary = true;
        if (charBinaryNum.length >= 8) {
            for (int i = 0; i < charBinaryNum.length; i++) {
                if (charBinaryNum[i] != '0' && charBinaryNum[i] != '1') {
                    isBinary = false;
                    break;
                }
            }
        } else {
            isBinary = false;

        }
        return isBinary;
    }
    
    
    public boolean isHexadecimal(String number){
    
        
        
        return false;
    }
}
